﻿using System;
using System.Windows.Media;

namespace CharacterModel
{
    public static class Utility
    {
        public static DrawingVisual GetScaledDrawingVisual(Action<DrawingContext> drawingFunction, int pixelWidth, int pixelHeight, int paddingAmount)
        {
            var drawingVisual = new DrawingVisual();
            using (var drawingContext = drawingVisual.RenderOpen())
                drawingFunction(drawingContext);

            var width = Math.Ceiling(drawingVisual.ContentBounds.Width);
            var height = Math.Ceiling(drawingVisual.ContentBounds.Height);
            var xScale = (pixelWidth - paddingAmount)/width;
            var yScale = (pixelHeight - paddingAmount)/height;
            var scale = Math.Min(xScale, yScale);

            var transformGroup = new TransformGroup();
            transformGroup.Children.Add(new TranslateTransform(-drawingVisual.ContentBounds.Left, -drawingVisual.ContentBounds.Top));
            transformGroup.Children.Add(new ScaleTransform(scale, scale));
            transformGroup.Children.Add(new TranslateTransform(paddingAmount, paddingAmount));
            drawingVisual.Transform = transformGroup;
            return drawingVisual;
        }
    }
}